package com.hm.common.common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.Calendar;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

/**
 * @author shishun.wang
 * @date 下午2:31:14 2016年6月8日
 * @version 1.0
 * @describe
 */
@SuppressWarnings("unused")
public class FileUtil {

	public static Integer hashCode(String url) throws FileNotFoundException {
		File file = new File(url);
		if (null == file) {
			throw new FileNotFoundException(url + "文件没找到");
		}
		return file.hashCode();
	}

	public static String generationNewFilePath(String tag) throws Exception {
		StringBuffer buffer = new StringBuffer(tag);
		Calendar cal = Calendar.getInstance();
		buffer.append("/" + cal.get(Calendar.YEAR));
		buffer.append("/" + (cal.get(Calendar.MONTH) + 1));
		buffer.append("/" + cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-"
				+ cal.get(Calendar.DAY_OF_MONTH));
		return buffer.toString();
	}

	public static String getExtensionName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length() - 1))) {
				return filename.substring(dot + 1);
			}
		}
		return filename;
	}

	public static java.io.File exists(String url, boolean isMkdir) throws Exception {
		File file = new File(url);
		if (!file.exists()) {
			if (!isMkdir)
				throw new FileNotFoundException(url);
			file.mkdirs();
		}
		return file;
	}

	/**
	 * 文件写入
	 *
	 * @param path
	 * @param data
	 * @throws Exception
	 */
	public static void writer(String path, String data) throws Exception {
		File file = new File(path);
		if (file.exists()) {
			file.delete();
		} else {
			file.getParentFile().mkdirs();
		}
		FileOutputStream fileOutputStream = null;
		OutputStreamWriter outputStreamWriter = null;
		BufferedWriter bufferedWriter = null;
		try {
			fileOutputStream = new FileOutputStream(file);
			outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
			bufferedWriter = new BufferedWriter(outputStreamWriter);
			bufferedWriter.write(data);
			bufferedWriter.flush();
			bufferedWriter.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != bufferedWriter)
				bufferedWriter.close();
			if (null != outputStreamWriter)
				outputStreamWriter.close();
			if (null != fileOutputStream)
				fileOutputStream.close();
		}
	}

	public static String read(String path) throws Exception {
		BufferedReader bufferedReader = null;
		InputStreamReader inputStreamReader = null;

		try {
			inputStreamReader = new InputStreamReader(new FileInputStream(path), "UTF-8");
			bufferedReader = new BufferedReader(inputStreamReader);

			StringBuffer buffer = new StringBuffer("");
			String line = null;
			while (null != (line = bufferedReader.readLine())) {
				buffer.append(line);
			}
			return buffer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != bufferedReader)
				bufferedReader.close();
			if (null != inputStreamReader)
				inputStreamReader.close();
		}
		return null;
	}

	/**
	 * 拷贝文件
	 *
	 * @param path
	 * @param data
	 * @throws Exception
	 */
	public static void copyFile(String path, String data) throws Exception {
		File file = new File(path);
		if (!file.exists()) {
			writer(path, data);
		}
	}

	/**
	 * 删除文件
	 *
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public static boolean deleteFile(String path) throws Exception {
		File file = new File(path);
		if (file.exists()) {
			return file.delete();
		}
		return true;
	}

	/**
	 * 删除指定目录下所有的文件
	 *
	 * @param file
	 *            new File("e:/tmp/");
	 * @throws Exception
	 */
	public static void clearAllFile(File file) throws Exception {
		if (file.isDirectory()) {
			File[] files = file.listFiles();
			if (null != files) {
				for (File tmpFile : files) {
					clearAllFile(tmpFile);
				}
			}
		}
		file.delete();
	}

	/**
	 * 检查远程文件是否存在
	 *
	 * @param remotePath
	 * @return
	 * @throws Exception
	 */
	public static boolean remoteFileExists(String remotePath) throws Exception {
		try {
			new URL(remotePath).openConnection().getInputStream();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static void download(String path, String fileName, HttpServletResponse response) throws Exception {
		InputStream inputStream = new BufferedInputStream(new FileInputStream(path));
		byte[] buffer = new byte[inputStream.available()];
		inputStream.read(buffer);
		inputStream.close();

		File file = new File(path);
		response.reset();
		// 设置response的Header
		response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
		response.addHeader("Content-Length", "" + file.length());
		OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
		// response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setContentType("binary/octet-stream");
		outputStream.write(buffer);
		outputStream.flush();
		outputStream.close();
	}

	public static UploadFile upload(String prefix, MultipartFile[] files) throws Exception {
		UploadFile uploadFile = new UploadFile();

		String fileName = null;
		for (MultipartFile multipartFile : files) {
			if (!multipartFile.isEmpty()) {
				fileName = multipartFile.getOriginalFilename();
				String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);

				String path = FileUtil.generationNewFilePath("");
				{// 判断文件夹存在否
					FileUtil.exists(prefix + "/" + path, true);
				}
				path += "/" + CommonUtil.generationToken() + "." + suffix;
				FileOutputStream os = new FileOutputStream(prefix + "/" + path);
				InputStream in = multipartFile.getInputStream();
				int b = 0;
				while ((b = in.read()) != -1) {
					os.write(b);
				}
				os.flush();
				os.close();
				in.close();

				uploadFile.setUploadPath(prefix + path);
			}
		}
		uploadFile.setFileName(fileName);

		return uploadFile;
	}

	public static class UploadFile {

		private String fileName;

		private String uploadPath;

		public String getFileName() {
			return fileName;
		}

		public void setFileName(String fileName) {
			this.fileName = fileName;
		}

		public String getUploadPath() {
			return uploadPath;
		}

		public void setUploadPath(String uploadPath) {
			this.uploadPath = uploadPath;
		}

	}

	public static void copy(File current, File target) throws IOException {
		FileInputStream inputStream = null;
		FileOutputStream outputStream = null;
		try {
			inputStream = new FileInputStream(current);
			outputStream = new FileOutputStream(target);
			byte buffer[] = new byte[1024 * 1024];
			int len = 0;
			while ((len = inputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, len);
			}
			outputStream.flush();
			outputStream.close();
		} finally {
			if (null != outputStream) {
				outputStream.close();
			}
			if (null != inputStream) {
				inputStream.close();
			}
		}
	}
}
